package com.im.app.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.im.app.authConfig.CurrentUser;
import com.im.app.authConfig.RequireLogin;
import com.im.app.mapper.DoyumingMapper;
import com.im.app.model.Doyuming;
import com.im.app.model.Personhost;
import com.im.app.model.User;
import com.im.app.model.YunConfig;
import com.im.app.service.IPersonhostService;
import com.im.app.service.IUserService;
import com.im.app.service.IYunConfigService;
import com.im.app.utils.*;
import org.jim.core.ImPacket;
import org.jim.core.packets.Command;
import org.jim.core.packets.RespBody;
import org.jim.server.JimServerAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/qr")
public class QRController extends BaseController{
    private static Logger logger = LoggerFactory.getLogger(QRController.class);
    @Resource
    IPersonhostService personhostService;
    @Resource
    private IUserService userService;

    @Resource
    private IYunConfigService configService;
    @Resource
    private DoyumingMapper doyumingMapper;

    @GetMapping("/notice")
    public void notice(String userId,String type,String message){

        Map<String,Object> map = new HashMap<>();
        map.put("type",type);
        map.put("message",message);
        ImPacket imPacket = new ImPacket(Command.COMMAND_ON_NOTICE_CHANGE_DOMAIN,new RespBody(Command.COMMAND_ON_NOTICE_CHANGE_DOMAIN,map).toByte());
        JimServerAPI.sendToUser(userId,imPacket);
    }

    @GetMapping(value = "/image")
    public void image(String content, HttpServletResponse response) {
        logger.info(content);
        try {
            OutputStream os = response.getOutputStream();
            QrCodeUtil.encode(content, "", os);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @RequireLogin
    @GetMapping(value = "/getAll")
    public ResponseResult<Object> getAll(@CurrentUser User user) {
        if(user == null || user.getUserId() == null){
            return Response.makeErrRsp("用户不存在");
        }
        List<Personhost> list = personhostService.getAll(user.getUserId());
        return Response.makeOKRsp(list);
    }

    @RequireLogin
    @GetMapping(value = "/updateHost")
    public ResponseResult<Personhost> updateHost(@CurrentUser User user,Integer id) {
        if(user == null || user.getUserId() == null){
            return  Response.makeErrRsp("用户不存在");
        }
        //分配备用入口
        return personhostService.backUpOpration(user, id);
    }

    @GetMapping(value = "/updateHostPage")
    public ResponseResult<Personhost> updateHostPage(String kamicode,Integer id) {
        if(StringUtils.isEmpty(kamicode)){
            return  Response.makeErrRsp("卡密不能为空");
        }
        if (null==id){
            return  Response.makeErrRsp("请选择要更改的二维码");
        }
        User user = userService.getUserBykamiCode(kamicode);
        if(user == null || user.getUserId() == null){
            return  Response.makeErrRsp("卡密有误");
        }

        return personhostService.backUpOpration(user, id);
    }

    @RequireLogin
    @GetMapping(value = "/updateCode")
    public ResponseResult<Object> updateCode(@CurrentUser User user,Integer id) {
        if(user == null || user.getUserId() == null){
           return Response.makeErrRsp("用户不存在");
        }
        String code = getCode();
        Personhost  personhost = new Personhost();
        personhost.setId(id);
        personhost.setUserId(user.getUserId());
        personhost.setShortcode(code);
        boolean update = personhostService.updateById(personhost);
        if (update){
            return Response.makeOKRsp().setData(personhost);
        }
        return Response.makeErrRsp("更新失败");
    }

    @RequireLogin
    @GetMapping("/getAllDynamicUrl")
    private ResponseResult<Object> getAllDynamicUrl(@CurrentUser User user){
        if(user == null || user.getUserId() == null){
            return Response.makeErrRsp("用户不存在");
        }
        QueryWrapper<Personhost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        queryWrapper.eq("leixing",10);
        queryWrapper.orderByDesc("create_time");
        List<Personhost> list = personhostService.list(queryWrapper);
        return Response.makeOKRsp(list);
    }

    @RequireLogin
    @GetMapping(value = "/createDynamicUrl")
    public ResponseResult<Object> createDynamicUrl(@CurrentUser User user) {
        if(user == null || user.getUserId() == null){
            return Response.makeErrRsp("用户不存在");
        }
        Personhost  personhost = new Personhost();
        personhost.setUserId(user.getUserId());
        personhost.setLeixing(10);
        QueryWrapper<Personhost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", user.getUserId());
        queryWrapper.eq("leixing", 10);
        long count = personhostService.count(queryWrapper);
        if (count >= 10){
            return Response.makeErrRsp("当前活码域名数量已达到最大");
        }
        Doyuming doyuming = doyumingMapper.selectDoyumingBYOne("11");
        Doyuming doyuming1 = doyumingMapper.selectDoyumingBYOne("10");
        if (doyuming != null && doyuming1 != null){
            String code = getCode();
            Personhost personhost1 = new Personhost();
            personhost1.setUserId(user.getUserId());
            personhost1.setLeixing(10);
            personhost1.setShortcode(code);
            personhost1.setDomain(doyuming1.getDomain());
            personhost1.setUrl(doyuming.getDomain());
            personhost1.setStatus(2);
            personhost1.setUpdateTime(new Date());
            boolean save = personhostService.save(personhost1);
            if (save){
                doyuming.setIsUse(1);
                if (doyuming.getUseTime() == null){
                    doyuming.setUseTime(new Date());
                }
                doyuming.setFenpeicount(doyuming.getFenpeicount() + 1);
                doyumingMapper.updateById(doyuming);
                doyuming1.setIsUse(1);
                if (doyuming1.getUseTime() == null){
                    doyuming1.setUseTime(new Date());
                }
                doyuming1.setFenpeicount(doyuming1.getFenpeicount() + 1);
                doyumingMapper.updateById(doyuming1);
                return Response.makeOKRsp();
            }
        }
        return Response.makeErrRsp("创建失败");
    }

    @RequireLogin
    @GetMapping(value = "/changeDynamicUrl")
    public ResponseResult<Object> changeDynamicUrl(@CurrentUser User user,Integer id) {
        if(user == null || user.getUserId() == null){
            return Response.makeErrRsp("用户不存在");
        }

        Personhost personhost = personhostService.getById(id);
        if (personhost == null){
            return Response.makeErrRsp("当前数据异常");
        }

        Doyuming doyuming = doyumingMapper.selectDoyumingBYOne1(personhost.getDomain());
        if (doyuming != null){

            doyuming.setIsUse(1);
            if (doyuming.getUseTime() == null){
                doyuming.setUseTime(new Date());
            }
            doyuming.setFenpeicount(doyuming.getFenpeicount() + 1);
            doyumingMapper.updateById(doyuming);

            personhost.setDomain(doyuming.getDomain());
            personhost.setUpdateTime(new Date());
            personhostService.updateById(personhost);
            return Response.makeOKRsp();
        }
        return Response.makeErrRsp("更新失败");
    }

    @RequireLogin
    @GetMapping(value = "/deletedDynamicUrl")
    public ResponseResult<Object> deletedDynamicUrl(@CurrentUser User user,Integer id) {
        if(user == null || user.getUserId() == null){
            return Response.makeErrRsp("用户不存在");
        }
        Personhost byId = personhostService.getById(id);
        if (byId == null){
            return Response.makeErrRsp("没有该数据");
        }
        personhostService.removeById(id);
        return Response.makeOKRsp();
    }


    private String getCode(){
        String code = RandomNum.randomxiaoxie(4);
        QueryWrapper<Personhost> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("shortcode", code);
        Personhost personhost = personhostService.getOne(queryWrapper);
        if (personhost != null){
            return getCode();
        }
        return code;
    }


    private Integer changeURL(String oldURL, String newURL,String title,String key){
        title = title.replaceAll(" ","");
        String checkURL = "https://gd-89emhe41.gaapqcloud.com.cn/api/lonre/?key="+key+"&old_url="+oldURL+"&new_url="+newURL+"&title="+title;
        String content = HttpUtils.sendGet(checkURL);
        logger.info(content);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(content);
        return jsonObject.getInteger("code");
    }
    private JSONObject createURL(String url,String title,String beizhu,String key){
        title = title.replaceAll(" ","");
        beizhu = beizhu.replaceAll("-LG","");
        beizhu = beizhu.replaceAll("LL-","");
        String checkURL = "http://gd-89emhe41.gaapqcloud.com.cn/api/long/act/create/?type=1&key="+key+"&url="+url+"&title="+title+"&beizhu="+beizhu;
        String content = HttpUtils.sendGet(checkURL);
        logger.info(content);
        return (JSONObject) JSONObject.parse(content);
    }



    @GetMapping(value = "/updateCodePage")
    public ResponseResult<Object> updateCodePage(String kamicode,Integer id) {
        if(StringUtils.isEmpty(kamicode)){
            return  Response.makeErrRsp("卡密不能为空");
        }
        if (null==id){
            return  Response.makeErrRsp("请选择要更改的二维码");
        }
        User user = userService.getUserBykamiCode(kamicode);
        if(user == null || user.getUserId() == null){
            return  Response.makeErrRsp("卡密有误");
        }
        String code = getCode();
        Personhost personhost = new Personhost();
        personhost.setId(id);
        personhost.setUserId(user.getUserId());
        personhost.setShortcode(code);
        boolean update = personhostService.updateById(personhost);
        if(update){
            return Response.makeOKRsp().setData(personhost);
        }
        return Response.makeErrRsp("更新失败");
    }

    @RequireLogin
    @GetMapping(value = "/repair")
    public ResponseResult<Object> repair(@CurrentUser User user) {
        if(user == null || user.getUserId() == null){
            return Response.makeErrRsp("用户不存在");
        }
        //分配备用落地
        personhostService.repairOpration(user);
        return Response.makeOKRsp("更新成功");
    }

    @GetMapping(value = "/repairPage")
    public ResponseResult<Object> repair(String kamicode) {
        if(StringUtils.isEmpty(kamicode)){
            return  Response.makeErrRsp("卡密不能为空");
        }
        User user = userService.getUserBykamiCode(kamicode);
        if(user == null || user.getUserId() == null){
            return  Response.makeErrRsp("用户不存在");
        }
        //分配备用落地
        personhostService.repairOpration(user);
        return Response.makeOKRsp("更新成功");
    }


    /**
     * 获取二维码
     *
     * */
    @GetMapping(value = "/getCode")
    public ResponseResult<Object> getCode(String kamicode) {
        if(StringUtils.isEmpty(kamicode)){
            return  Response.makeErrRsp("卡密不能为空");
        }
        User user = userService.getUserBykamiCode(kamicode);
        if(user == null || user.getUserId() == null){
            return  Response.makeErrRsp("卡密有误");
        }
        List<Personhost> list = personhostService.getAll(user.getUserId());
        Map map = new HashMap();
        map.put("list",list);
        map.put("avatar",user.getAvatar());
        return Response.makeOKRsp(map);
    }
}
